<template>
  <div>
    <!-- 当前cid为：{{ cId }} -->
    <!-- {{formartCategoryTreeInfo(ArticleAddform.aCategoryId)}} -->
    <!-- 分类对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="categoryDialogVisible"
      width="30%"
      :before-close="handleClose"
      append-to-body
    >
      <el-cascader
        placeholder="请选择，支持搜索功能，默认为根节点分支"
        style="width: 400px"
        v-model="ArticleAddform.PidArr"
        :options="options"
        filterable
        :props="{ checkStrictly: true, expandTrigger: 'hover' }"
        :key="iscascaderShow"
      ></el-cascader>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="changeCategorySubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handledialogClose"
      append-to-body
    >
      <!-- <span>这是一段信息</span> -->
      <el-image :src="dialogVisibleSrc"> </el-image>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span> -->
    </el-dialog>
    <!-- 上传文件对话框 -->
    <el-dialog
      title="上传图片"
      :visible.sync="uploadDialogVisible"
      width="50%"
      :before-close="handleUploadDialogClose"
      append-to-body
    >
      <Upload
        @uploadSuccess="handleUploadSuccess"
        :url="uploadUrl"
        ref="uploadElement"
      ></Upload>
    </el-dialog>
    <el-row>
      <el-steps :active="active" finish-status="success">
        <el-step title="步骤1"></el-step>
        <el-step title="步骤2"></el-step>
        <el-step title="步骤3"></el-step>
      </el-steps>
    </el-row>
    <el-row type="flex" justify="center">
      <!-- 主体内容区 -->
      <el-col :span="20" v-show="active <= 1">
        <h2 style="text-align: center">
          步骤1：写文章的相关信息：标题、简介等
        </h2>
        <el-form
          ref="addArticleForm"
          :model="ArticleAddform"
          label-width="80px"
          :rules="rules"
        >
          <el-form-item label="文章标题" prop="aTitle">
            <el-input v-model="ArticleAddform.aTitle"></el-input>
          </el-form-item>
          <el-form-item label="所属分类" prop="aCategoryId">
            <el-col :span="18">
              <el-input
                disabled
                v-model="ArticleAddform.aMajorCategoryTreeInfo"
              >
              </el-input>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="changeCategory">更改</el-button>
              <el-button type="warning" plain @click="addToCategory"
                >添加到其他分类</el-button
              >
            </el-col>
            <el-row v-for="(item, index) in extraCategories" :key="index">
              <el-col :span="18">
                <el-input disabled v-model="item.cTree"></el-input>
              </el-col>
              <el-col :span="6">
                <el-button type="danger" @click="delExtraCategory(index)"
                  >删除</el-button
                >
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="作者" prop="aAuthorName">
            <el-input v-model="ArticleAddform.aAuthorName"></el-input>
          </el-form-item>
          <el-form-item label="来源" prop="aComeFrom">
            <el-input v-model="ArticleAddform.aComeFrom"></el-input>
          </el-form-item>
          <el-form-item label="文章简介" prop="aDescribe">
            <el-input
              type="textarea"
              v-model="ArticleAddform.aDescribe"
            ></el-input>
          </el-form-item>
          <el-form-item label="文章状态" prop="aStatus">
            <el-radio-group v-model="ArticleAddform.aStatus">
              <el-radio :label="0">草稿</el-radio>
              <el-radio :label="1">待审核</el-radio>
              <el-radio :label="2">一审通过</el-radio>
              <el-radio :label="3">二审通过</el-radio>
              <el-radio :label="4">终审通过</el-radio>
              <!-- <el-radio label="草稿" value="0"></el-radio> -->
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="20" v-show="active == 2">
        <h2 style="text-align: center">
          步骤2：上传文件相关的资源，指定文章大图
        </h2>
        <el-row>
          <el-row type="flex" justify="space-between">
            <el-col :span="4">
              <el-date-picker
                v-model="searchDate"
                type="month"
                placeholder="请选择要查找的月"
                format="yyyy 年 MM 月 "
                value-format="yyyy-MM"
                style="width: 100%"
              >
              </el-date-picker>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" size="medium" @click="handleSearch"
                >查找</el-button
              >
              <el-button type="primary" size="medium" @click="handleUpload"
                >上传文件</el-button
              >
            </el-col>
            <el-col :span="14">
              <span>绑定的大图：</span
              ><el-input
                type="text"
                v-model="ArticleAddform.aTitlePicId"
                disabled
                style="width: 10%"
              ></el-input>
              <el-select
                placeholder="已被关联的图片"
                multiple
                default-first-option
                :value="selectvalue"
                style="margin-left: 1em"
              >
                <el-option
                  v-for="(item, index) in relationPictures"
                  :key="item.sId"
                  :label="item.sName"
                  :value="item.sId"
                >
                  <span style="float: left">{{ item.sName }}</span>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    size="mini"
                    @click="() => removeNode(index)"
                    style="margin-left: 1em; color: #8492a6; font-size: 13px"
                  >
                  </el-button>
                </el-option>
              </el-select>
              <el-button
                type="info"
                style="margin-left: 1em"
                size="medium"
                @click="handleImportToContent"
                >导入到正文中</el-button
              >
            </el-col>
          </el-row>
          <el-row
            :gutter="10"
            class="pictureManagePanel"
            type="flex"
            justify="start"
            style="flex-wrap: wrap; flex-direction: row"
          >
            <el-col :span="4" v-for="item in sources" :key="item.sId">
              <picture-card-for-article-add
                :data="item"
                @handlePreview="handlePreviewOn"
                @pictureCardAddToTitlePic="handleAddToTitlePic"
                @pictureCardAddToRelationPic="handelAddToRelationPic"
              ></picture-card-for-article-add>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[18, 24, 30, 36]"
              :page-size="size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
          </el-row>
        </el-row>
      </el-col>
      <el-col :span="20" v-show="active > 2">
        <h2 style="text-align: center">步骤3：在富文本编辑器中写文章的正文</h2>
        <!-- <mavon-editor
          v-model="ArticleAddform.aContent"
          :ishljs="true"
          ref="md"
          @imgAdd="$imgAdd"
          @imgDel="$imgDel"
          style="height: 800px"
        /> -->
        <mavon-editor
           v-model="ArticleAddform.aContent"
          ref="md"
          @imgAdd="$imgAdd"
          @imgDel="$imgDel"
          :subfield="subfield"
          :code_style="code_style"
          :ishljs="true"
          :externalLink="externalLink"
        ></mavon-editor>
      </el-col>
    </el-row>

    <el-row type="flex" justify="center">
      <el-col :span="4">
        <el-button style="margin-top: 12px" @click="pre" v-show="active > 1"
          >上一步</el-button
        >
        <el-button style="margin-top: 12px" @click="next" v-show="active < 3"
          >下一步</el-button
        >
        <el-button
          style="margin-top: 12px"
          @click="submitForm"
          v-show="active == 3"
          >点击提交</el-button
        >
      </el-col>
    </el-row>
  </div>
</template>


<script>
import { GetCategoryTreeById, getCategoryTree,addArticle } from "@/api/api";
import PictureCard from "@/components/PictureCard.vue";
import pictureCardForArticleAdd from "@/components/PictureCardForArticleAdd.vue";
import { getSourceListPage, removeSource } from "@/api/api";
import Upload from "@/components/Upload/Upload.vue";
import { siteUrl } from "@/api/constTools";
import { fileSiteUrl } from "@/api/constTools";

export default {
  components: { Upload, Upload, pictureCardForArticleAdd },
  data() {
    return {
      // mavonEditor
      subfield: true,
      code_style: "solarized-dark",
      externalLink: {
        markdown_css: function () {
          // 这是你的markdown css文件路径
          return "@/assets/mavon-editor/dist/markdown/github-markdown.min.css";
        },
        hljs_js: function () {
          // 这是你的hljs文件路径
          return "@/assets/mavon-editor/dist/highlightjs/highlight.min.js";
        },
        hljs_css: function (css) {
          // 这是你的代码高亮配色文件路径
          return (
            "@/assets/mavon-editor/dist/highlightjs/styles/" + css + ".min.css"
          );
        },
        hljs_lang: function (lang) {
          // 这是你的代码高亮语言解析路径
          return (
            "@/assets/mavon-editor/dist/highlightjs/languages/" +
            lang +
            ".min.js"
          );
        },
        katex_css: function () {
          // 这是你的katex配色方案路径路径
          return "@/assets/mavon-editor/dist/katex/katex.min.css";
        },
        katex_js: function () {
          // 这是你的katex.js路径
          return "@/assets/mavon-editor/dist/katex/katex.min.js";
        },
      },

      selectvalue: [], //给select一个value，不报错
      // source start
      searchDate: null, //默认搜索时间为当月时间
      // sType: 0,
      // 分页
      page: 1,
      total: 0,
      size: 18,
      sources: [],

      // 图片预览
      dialogVisible: false,
      dialogVisibleSrc: "",

      // 上传文件对话框
      uploadDialogVisible: false,
      uploadUrl: siteUrl + "api/source",
      // source end

      active: 0,

      //   article 相关
      ArticleAddform: {
        aId: 1,
        aTitle: "",
        aDescribe: "",
        aContent: "",
        aTitlePicId: 10, //默认设置大图为10号
        // aTitlePicPath: "source\\2022-10\\133097807178522548.jpg",
        aStatus: 1, //默认设置文章状态为待审核
        aWeight: 0,
        // aUpdateTime: "2022-10-26T20:03:08+08:00",
        aIsDeleted: false,
        aVisitCount: 0,
        // aEditorId: 12,
        // aEditorRealName: "后台总管理员",
        aAuthorName: "",
        aComeFrom: "",
        // aCreateTime: "2022-10-26T20:03:08+08:00"

        // 单独为分类加的属性
        aCategoryId: 0, //默认应该为从父组件中传过来的cid
        aMajorCategoryTreeInfo: "",
        PidArr: [],
        aExtraCategoryId: [], //要添加到的其他分类数组id

        aRelationPic:[] //要添加的资源数组，与aTitlePicId不重复
      },
      extraCategories: [], //要添加到的其他分类数组

      //关联的图片数组
      relationPictures: [],

      // 表单验证
      rules: {
        aTitle: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          { min: 1, max: 50, message: "长度不能超过50个字符", trigger: "blur" },
        ],
        aCategoryId: [
          {
            type: "number",
            required: true,
            message: "分类不能为空",
            trigger: "blur",
          },
        ],
        aAuthorName: [
          { required: true, message: "请输入文章作者", trigger: "blur" },
          { min: 1, max: 20, message: "长度不能超过20个字符", trigger: "blur" },
        ],
        aComeFrom: [
          { required: true, message: "请输入文章来源", trigger: "blur" },
          { min: 1, max: 20, message: "长度不能超过20个字符", trigger: "blur" },
        ],
        aDescribe: [
          {
            min: 0,
            max: 200,
            message: "长度不能超过200个字符",
            trigger: "blur",
          },
        ],
      },
      categoryDialogVisible: false,
      options: [], //用于在级联选择时存放数据
      iscascaderShow: 0,  //用于避免Cannot read properties of null (reading 'level')报错
      isChangeCategory: false, //用于判断Cascader是否是属于修改主分类
    };
  },
  props: ["cId"],
  // 监听cid
  watch: {
    async cId(val) {
      // console.log("watched: "+val);
      this.ArticleAddform.aCategoryId = val;
      // 更新aMajorCategoryTreeInfo数据
      var result = await GetCategoryTreeById(this.ArticleAddform.aCategoryId);
      // console.log(result);
      this.ArticleAddform.aMajorCategoryTreeInfo = result.data.response;
    },
  },
  async mounted() {
    var result = await GetCategoryTreeById(this.ArticleAddform.aCategoryId);
    // console.log(result);
    this.ArticleAddform.aMajorCategoryTreeInfo = result.data.response;
    //  console.log(this.ArticleAddform.aMajorCategoryTreeInfo);
    //  this.ArticleAddform.aMajorCategoryTreeInfo= this.formartCategoryTreeInfo(this.ArticleAddform.aCategoryId);
    //  console.log(this.ArticleAddform.aMajorCategoryTreeInfo);

    // 指定搜索时间为当前时间：2022-10
    var d = new Date();
    // console.log(d);
    this.searchDate = d.getFullYear() + "-" + (d.getUTCMonth() + 1);
    // 此处为什么要加1，因为getMonth拿到的下标是从0开始的！
    // console.log(this.searchDate);

    if (this.active == 0) {
      this.active++;
    }
  },
  methods: {
    // 已关联的图片方法开始
    removeNode(index) {
      this.relationPictures.splice(index, 1);
    },
    handleImportToContent() {
      // 拿到所有的relationPictures，将其转换为img元素，再加到content中
      let imgContent = "";
      // this.relationPictures.forEach((item) => {
      //   let img = `<div class="hljs-center"><img src="${item.sPath}" /></div>`;
      //   imgContent += img;
      // });
      this.relationPictures.forEach((item) => {
        let img = `<img src="${item.sPath}" />`;
        imgContent += img;
      });
      // 尝试更改为向md的html中添加元素
      // console.log(this.$refs.md.d_render);
      // this.$refs.md.d_render+=imgContent;
      // console.log(this.$refs.md.d_render);
      // let imgTag = "";
      // this.relationPictures.forEach((item,index) => {
      //   let img = `!["${item.sId}"](${index})`;
      //   imgTag += img;
      // });
      // console.log(imgTag);
      // this.$refs.md.d_value+=imgTag;
      // console.log(imgContent);
      this.ArticleAddform.aContent += imgContent;
      this.$message.success("导入成功");
    },
    // 已关联的图片方法结束

    // source method start
    handleSearch() {
      // this.$message.info("search");
      this.getSources();
    },
    handleUpload() {
      // this.$message.info("upload");
      this.uploadDialogVisible = true;
    },
    handleUploadSuccess(data) {
      // 拿到上传组件上传成功时后台返回的数据列表
      // this.relationPictures.push(data);
      // 在向关联图片添加内容时要加上图片的全路径，否则加到mavon editor中无法正常显示
      data.forEach((item) => {
        item.sPath = fileSiteUrl + item.sPath;
      });
      // console.log(data);
      this.relationPictures.push.apply(this.relationPictures, data);
      // console.log(this.relationPictures);
      this.getSources(); //上传成功后再一次更新数据
    },
    getSources() {
      let para = {
        pageIndex: this.page,
        pageSize: this.size,
        searchDate: this.searchDate,
        sType: this.sType,
        // key: this.filters.name
      };
      // this.listLoading = true;

      //NProgress.start();
      getSourceListPage(para).then((res) => {
        // console.log(res.data);
        this.sources = res.data.data;
        this.total = res.data.dataCount;
        // console.log(this.sources);
        // this.listLoading = false;
        //NProgress.done();
      });
    },
    handlePreviewOn(val) {
      // this.$message.info("receive from child");
      // console.log(val);
      // 显示遮罩层，将val传入并进行图片显示
      this.dialogVisible = true;
      this.dialogVisibleSrc = val;
    },
    handledialogClose() {
      this.dialogVisible = false;
    },
    handleUploadDialogClose() {
      this.uploadDialogVisible = false;
      // 关闭对话框后要清空已上传文件队列
      this.$refs["uploadElement"].clearFiles();
    },
    handleAddToTitlePic(val) {
      // console.log(val);
      this.ArticleAddform.aTitlePicId = val;
      this.$message.success(`设置文章大图为：${val}`);
    },
    handelAddToRelationPic(obj) {
      // console.log(obj);
      this.relationPictures.push(obj);
      this.$message.success("添加成功！");
    },
    //分页事件
    handleSizeChange(val) {
      this.size = val;
      this.getSources();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getSources();
    },
    // source method end

    // 步骤条方法
    next() {
      if (this.active < 3) {
        this.active = this.active + 1;
        this.$message.info(this.active);
      }
      // 进入第二步骤时才刷新图片数据
      if (this.active == 2) {
        this.getSources();
      }
      // if (this.active++ > 2) this.active = 2;
    },
    pre() {
      if (this.active > 1) this.active--;
      this.$message.info(this.active);
      // if (this.active-- < 0) this.active = 0;
      if (this.active == 2) {
        this.getSources();
      }
    },
    submitForm() {
      // 向后台提交数据前要对数据进行封装：关联图片、额外添加的分类
 
      var htmlValue=this.$refs.md.d_render;
      var oldMd=this.ArticleAddform.aContent;//保存好原来的数据，更新失败还可以用
      // 在执行axios方法时将数据改了html格式，如果成功清空内容即可，如果不成功，再改回去
      var that=this.ArticleAddform;
      that.aContent=htmlValue;
      //添加分类数据
      this.extraCategories.forEach(item=>{
        that.aExtraCategoryId.push(item.cId);
      });
      //添加Source数据
      this.relationPictures.forEach(item=>{
        that.aRelationPic.push(item.sId);
      });
      // console.log(that);
      this.$refs["addArticleForm"].validate((valid) => {
        if (valid) {
          // console.log(that);
          // this.$message.success("commit form");
          addArticle(that).then(res=>{
            //更新数据
            this.$emit("addSuccess",res.data)
          })
        } else {
          this.$message.error("表单内容未通过验证");
        }
      });
    },
    // 根据id找到树信息
    formartCategoryTreeInfo(val) {
      let result = "";
      GetCategoryTreeById(val).then((res) => {
        // console.log(res.data);
        result = res.data.response;
        console.log(result);
      });
      setTimeout(() => {
        console.log(result);
        return result;
      }, 1000);
    },
    // categoryDialog对话框
    handleClose(done) {
      // this.$confirm('确认关闭？')
      //     .then(_ => {
      //       done();
      //     })
      //     .catch(_ => {});
      // this.$message.info("handle close");
      this.categoryDialogVisible = false;
      this.isChangeCategory = false;
    },
    // 修改Category
    changeCategory() {
      this.isChangeCategory = true;

      let para = { pid: 0 };
      // 使用之前先清空
      this.options = [];
      // this.ArticleAddform.PidArr=[];此时不用清空，可以用来定位原数据
      getCategoryTree(para).then((res) => {
        ++this.iscascaderShow;
        this.options.push(res.data.response);
      });
      this.categoryDialogVisible = true;
    },
    // 添加到其他Category
    addToCategory() {
      let para = { pid: 0 };
      // 使用之前先清空
      this.options = [];
      this.ArticleAddform.PidArr = [];

      getCategoryTree(para).then((res) => {
        ++this.iscascaderShow;
        this.options.push(res.data.response);
      });
      this.categoryDialogVisible = true;
    },
    async changeCategorySubmit() {
      console.log(this.isChangeCategory);
      if (this.isChangeCategory) {
        // 如果是更新Category
        // 拿到PidArr的最后一项就是用户选中的数据id
        let count = this.ArticleAddform.PidArr.length;
        this.ArticleAddform.aCategoryId = this.ArticleAddform.PidArr[count - 1];
        var promise = await GetCategoryTreeById(
          this.ArticleAddform.aCategoryId
        );
        this.ArticleAddform.aMajorCategoryTreeInfo = promise.data.response;
        this.categoryDialogVisible = false;
        this.isChangeCategory = false;
        // this.$message.error("123123");
      } else {
        // 如果是添加Category
        // 拿到PidArr的最后一项就是用户选中的数据id
        let count = this.ArticleAddform.PidArr.length;
        // 将新的Category信息存到数组中
        var category = {};
        category.cId = this.ArticleAddform.PidArr[count - 1];
        if (category.cId == 0) {
          this.$message.error("不要在根节点下添加内容");
          return;
        }
        if (category.cId == this.ArticleAddform.aCategoryId) {
          this.$message.error("不要重复添加相同的分类");
          return;
        }
        let isAlreadyInArr = false;
        this.extraCategories.forEach(function (item, index, arr) {
          if (item.cId == category.cId) {
            isAlreadyInArr = true;
          }
        });
        if (isAlreadyInArr) {
          this.$message.error("不要重复添加相同的分类");
          return;
        }
        var promise = await GetCategoryTreeById(category.cId);
        category.cTree = promise.data.response;
        this.extraCategories.push(category);
        // console.log(this.extraCategories);
        this.categoryDialogVisible = false;
      }
    },
    // 删除用户指定的ExtraCategory
    delExtraCategory(index) {
      //  console.log(index);
      this.extraCategories.splice(index, 1);
    },

    // mavonEditor
    $imgAdd(pos, $file) {
      this.$message.info("此功能未开放，请从步骤2上传资源！");
      return;
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      formdata.append("image", $file);
      this.img_file[pos] = $file;
      this.$http({
        url: "/api/edit/uploadimg",
        method: "post",
        data: formdata,
        headers: { "Content-Type": "multipart/form-data" },
      }).then((res) => {
        let _res = res.data;
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        this.$refs.md.$img2Url(pos, _res.url);
      });
    },
    $imgDel(pos) {
      delete this.img_file[pos];
    },
  },
};
// 设置mavon editor高度为当前屏幕高度
var screen_height = window.screen.availHeight;
// var mavon_editor=document.getElementsByClassName("v-note-panel");
// mavon_editor[0].style.height=screen_height;
// console.log(screen_height);
// console.log(mavon_editor);
</script>

<style scoped>
.pictureManagePanel {
  width: 100%;
  height: max-content;
  /* border: 3px solid paleturquoise; */
  padding: 10px 0%;
}
.markdown-body {
  height: 834px !important;
}
</style>